package 排序算法;

import java.util.Arrays;
import java.util.Collections;

/**
 * @author kakayubei
 * @description
 * @date 2021/10/17 23:23
 */
public class InsertionSort {
    public static int[] insertionSort(int[] sourceArr) {
        int[] arr = Arrays.copyOf(sourceArr, sourceArr.length);
        for (int i = 0, len = arr.length; i < len; i++) {
            int tmp = arr[i];
            for (int j = i; j > 0; j--) {
                if (tmp < arr[j - 1]) {
                    arr[i] = arr[j - 1];
                    arr[j - 1] = tmp;
                    tmp = arr[j - 1];
                }
            }
        }
        return arr;
    }

    public static int[] insertionSort2(int[] sourceArr) {
        int[] arr = Arrays.copyOf(sourceArr, sourceArr.length);
        for (int i = 0, len = arr.length; i < len; i++) {
            int tmp = arr[i];
            int j = i;
            while (j >0 && tmp < arr[j - 1]) {
                arr[j] = arr[j -1];
                j--;
            }
            if (j != i) {
                arr[j] = tmp;
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 3, 5, 3, 4, 9 };
        System.out.println(Arrays.toString(insertionSort(arr)));
    }
}
